import { getArrayRandomOne } from '../../../utils/Util'
import { tiandituArr as defaultTokenArr } from '../../../const/Token'

export class TdtImageryLayerProvider extends Cesium.WebMapTileServiceImageryProvider {
  constructor(options = {}) {
    let _layer
    let _key
    let maxLevel = 18

    switch (options.layer) {
      default:
      case 'vec_d':
        _layer = 'vec'
        break
      case 'vec_z':
        _layer = 'cva'
        break
      case 'img_d':
        _layer = 'img'
        break
      case 'img_z':
        _layer = 'cia'
        break
      case 'ter_d':
        _layer = 'ter'
        maxLevel = 14
        break
      case 'ter_z':
        _layer = 'cta'
        maxLevel = 14
        break
    }

    if (options.key == null || options.key.length == 0) {
      options.key = defaultTokenArr
    }
    _key = getArrayRandomOne(options.key)

    let _url
    if (options.crs == '4490' || options.crs == '4326') {
      //wgs84
      _url =
        'https://t{s}.tianditu.gov.cn/' +
        _layer +
        '_c/wmts?service=WMTS&version=1.0.0&request=GetTile&tilematrix={TileMatrix}&layer=' +
        _layer +
        '&style={style}&tilerow={TileRow}&tilecol={TileCol}&tilematrixset={TileMatrixSet}&format=tiles&tk=' +
        _key

      options = {
        subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
        maximumLevel: maxLevel,
        ...options,

        url: _url,
        layer: _layer,
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: 'c',
        tileMatrixLabels: [...Array(20).keys()].map((level) => (level + 1).toString()),
        tilingScheme: new Cesium.GeographicTilingScheme(),
      }
    } else {
      //墨卡托
      _url =
        'https://t{s}.tianditu.gov.cn/' +
        _layer +
        '_w/wmts?service=WMTS&version=1.0.0&request=GetTile&tilematrix={TileMatrix}&layer=' +
        _layer +
        '&style={style}&tilerow={TileRow}&tilecol={TileCol}&tilematrixset={TileMatrixSet}&format=tiles&tk=' +
        _key

      if (options.proxy || options.headers || options.queryParameters) {
        //存在代理等参数时
        _url = getUrlResource({
          url: _url.replace('{s}', '0'),
          proxy: options.proxy,
          headers: options.headers,
          queryParameters: options.queryParameters,
        })
      }

      options = {
        subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
        maximumLevel: maxLevel,
        ...options,

        url: _url,
        layer: _layer,
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: 'w',
        tileMatrixLabels: [...Array(20).keys()].map((level) => level.toString()),
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
      }
    }

    super(options)
  }
}
